﻿using System;
using System.Linq;
using System.Linq.Expressions;

namespace YanZhiwei.DotNet3._5.Utilities.Base
{
    /// <summary>
    /// ConditionalSelector
    ///<para>rel:http://www.cnblogs.com/ldp615/archive/2011/02/17/WhereIf-ExtensionMethod.html </para>
    /// </summary>
    public class ConditionalIQueryableSelector<T>
    {
        #region 构造函数以及变量
        private readonly IQueryable<T> source;
        private readonly bool condition;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="csource">IQueryable</param>
        /// <param name="ccondition">成立条件</param>
        public ConditionalIQueryableSelector(IQueryable<T> csource, bool ccondition)
        {
            this.source = csource;
            this.condition = ccondition;
        }
        #endregion
        #region ThenWhere
        /// <summary>
        /// ThenWhere
        /// <para>eg:source.If(String.IsNullOrEmpty(name) == false).ThenWhere(p => p.Name.Contains(name))</para>
        /// </summary>
        /// <param name="keySelector">委托</param>
        /// <returns>IQueryable</returns>
        public IQueryable<T> ThenWhere(Expression<Func<T, bool>> keySelector)
        {
            return condition ? source.Where(keySelector) : source;
        }
        #endregion 
    }

}
